package cz.zcu.fav.rat.dataaccess.dao.impl;

import genericdao.finder.FinderExecutor;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Query;

import org.hibernate.SessionFactory;

import cz.zcu.fav.rat.dataaccess.dao.GenericDAO;

public class GenericDaoHibernateImpl<T, PK extends Serializable> implements
		GenericDAO<T, PK>, FinderExecutor
{
	private Class<T> type;
	private SessionFactory sessionFactory;

	public SessionFactory getSessionFactory()
	{
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory)
	{
		this.sessionFactory = sessionFactory;
	}

	public GenericDaoHibernateImpl(Class<T> type)
	{
		this.type = type;
	}

	public List<T> getAll()
	{
		return getSession().createCriteria(type).list();
	}

	public PK create(T o)
	{
		return (PK) getSession().save(o);
	}

	public void saveOrUpdate(T o)
	{
		getSession().saveOrUpdate(o);
	}

	public T read(PK id)
	{
		return (T) getSession().get(type, id);
	}

	public void update(T o)
	{
		getSession().update(o);
	}

	public void delete(T o)
	{
		getSession().delete(o);
	}

	private Session getSession()
	{
		return getSessionFactory().getCurrentSession();
	}

	public String queryNameFromMethod(Method finderMethod)
	{
		return type.getSimpleName() + "." + finderMethod.getName();
	}

	@Override
	public List<T> executeFinder(Method method, Object[] queryArgs)
	{
		final String queryName = queryNameFromMethod(method);
		final Query namedQuery = getSession().getNamedQuery(queryName);
		String[] namedParameters = namedQuery.getNamedParameters();
		for (int i = 0; i < queryArgs.length; i++)
		{
			Object arg = queryArgs[i];
			// Type argType =
			namedQuery.setParameter(i, arg);
		}
		return namedQuery.list();
	}
	

	@Override
	public Iterator<?> iterateFinder(Method method, Object[] queryArgs)
	{
		return null;
	}

	@Override
	public T merge(T persistentObject)
	{
		return (T) getSession().merge(persistentObject);
		
	}
}